package controllers.administrator;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import security.UserAccount;
import services.AdministratorService;
import controllers.AbstractController;
import domain.Administrator;
import forms.AdminForm;

@Controller
@RequestMapping("/security/registration")
public class RegisterAdministratorController extends AbstractController {
	@Autowired
	private AdministratorService administratorService;

	//Constructors
	public RegisterAdministratorController(){
		super();
	}
	//Creation
	@RequestMapping(value = "/administrator", method = RequestMethod.GET)
	public ModelAndView registration() {
		ModelAndView result;
		AdminForm adminForm;
		Boolean isAdministrator = true;
		adminForm = new AdminForm();

		result = new ModelAndView("security/registration/administrator");
		result.addObject("adminForm", adminForm);
		result.addObject("isAdministrator", isAdministrator);

		return result;
	}
	//Edition
	@RequestMapping(value = "/administrator", method = RequestMethod.POST, params = "save")
	public ModelAndView save(@Valid AdminForm adminForm, BindingResult binding) {
		ModelAndView result;

		if (binding.hasErrors()) {
			result = createEditModelAndView(adminForm);
		} else {
			try {
				Administrator administrator = administratorService.reconstruct(adminForm);
				Md5PasswordEncoder encoder = new Md5PasswordEncoder();
				UserAccount user =administrator.getUserAccount();
				String password = user.getPassword();
				String hash = encoder.encodePassword(password, null);
				user.setPassword(hash);
				administrator.setUserAccount(user);
				administratorService.save(administrator);
				result = new ModelAndView("redirect:../../");

			} catch (Throwable oops) {

				result = createEditModelAndView(adminForm,
						"administrator.commit.error");
			}
		}

		return result;
	}
	
	//Ancillary methods
	protected ModelAndView createEditModelAndView(AdminForm administrator) {
		ModelAndView result;

		result = createEditModelAndView(administrator, null);

		return result;
	}

	protected ModelAndView createEditModelAndView(AdminForm administrator,
			String message) {
		ModelAndView result;
		String authority = "administrator";
		
		result = new ModelAndView("security/registration/administrator");

		result.addObject("administrator", administrator);
		result.addObject("authority", authority);
		result.addObject("message", message);

		return result;
	}

	
}
